<template>
  <div class="container">
    <el-table :data="assetList" v-loading="loading">
      <el-table-column label="物品名称" prop="name" />
      <el-table-column label="状态" width="auto">
        <template #default="{ row }">
          <ClassSelfCheckRow :data="row" :disabled="!isToday"/>
        </template>
      </el-table-column>
    </el-table>

    <!-- <div class="other-section mt-20px">
      <div class="other-title flex justify-between items-center">
        <span>其它事项</span>
        <ClassSelfCheckRow v-if="otherData.notes" :data="otherData" />
      </div>
      <el-input
        v-model="otherData.notes"
        type="textarea"
        placeholder="请输入其它需要说明的事项"
        :autosize="{ minRows: 3, maxRows: 6 }"
      />
    </div> -->

    <div v-if="isToday" class="mt-20px">
      <el-button type="primary" @click="saveCheck" :loading="saveLoading">保存</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ClassAssetCheckApi, ClassAssetCheck } from '@/api/school/classAffairs/check'
import { ClassAssetApi } from '@/api/school/classAffairs'
import ClassSelfCheckRow from './ClassSelfCheckRow.vue'
const message = useMessage() // 消息弹窗

const route = useRoute()
const props = defineProps({
  date: {
    type: String,
    default: ''
  },
  isToday: {
    type: Boolean,
    default: true
  }
})

const loading = ref(false)
const saveLoading = ref(false)
const assetList = ref<any[]>([])
const otherData = ref<any>({
  notes: '',
  status: 0
})
const checkData = ref<ClassAssetCheck>({
  id: 0,
  classId: 0,
  checkNotes: ''
})
const emit = defineEmits(['refresh'])
// 获取班级物品自检情况
const getClassAssetCheck = async () => {
  if (!props.date) return

  loading.value = true
  try {
    const data = await ClassAssetCheckApi.getClassAssetCheck({
      classId: route.query.id as string,
      queryDay: props.date
    })

    checkData.value = data
    if (data.checkNotes) {
      const notes = JSON.parse(data.checkNotes)
      // 分离物品列表和其它事项
      if (Array.isArray(notes)) {
        assetList.value = notes.filter((item: any) => item.id && item.name)
        // 查找是否有其它事项（没有id的项）
        const otherItem = notes.find((item: any) => !item.id)
        if (otherItem) {
          otherData.value.notes = otherItem.notes || ''
          otherData.value.status = otherItem.status
        }
      }
    } else {
      // 如果没有数据，则获取班级物品列表
      await getClassAssetList()
    }
  } catch (error) {
    // 如果查询失败，则获取班级物品列表
    await getClassAssetList()
  } finally {
    loading.value = false
  }
}

// 获取班级物品列表
const getClassAssetList = async () => {
  try {
    const params = {
      classId: route.query.id
    }
    const data = await ClassAssetApi.getClassAssetPage(params)
    // 初始化状态为正常(0)
    assetList.value = data.list.map((item: any) => ({
      id: item.id,
      name: item.name,
      status: 0
    }))
  } catch (error) {
    console.error('获取班级物品列表失败', error)
  }
}

// 保存检查结果
const saveCheck = async () => {
  if (!checkData.value.classId && route.query.id) {
    checkData.value.classId = Number(route.query.id)
  }

  saveLoading.value = true
  try {
    // 构造checkNotes数据
    const notesData = [...assetList.value]

    // 添加其它事项
    if (otherData.value.notes) {
      notesData.push({
        ...otherData.value
      })
    }

    const params = {
      ...checkData.value,
      checkNotes: JSON.stringify(notesData)
    }

    await ClassAssetCheckApi.updateClassAssetCheck(params)
    message.success('保存成功')
    emit('refresh')
  } catch (error) {
    message.error('保存失败')
  } finally {
    saveLoading.value = false
  }
}

watch(
  () => props.date,
  () => {
    getClassAssetCheck()
  },
  {
    immediate: true
  }
)
</script>

<style lang="scss" scoped>
.other-section {
  color: #666;

  .other-title {
    margin-bottom: 10px;
  }
}
</style>
